// 作业2：去计算生成1000个文件同步和异步的耗时,分别按uft8和ascii码的去读取每个文件的内容.
'use strict';
let fs = require("fs");
//同步
var StartTime = new Date().getTime();
if(!fs.existsSync("index")) fs.mkdirSync("index");
for (var i = 1; i < 1001; i++) {
    fs.writeFileSync("./index/" + i + ".txt", "你好");

}
var EndTime = new Date().getTime();
console.log("同步耗时为：" + (EndTime - StartTime));
//异步
var StartTime1 = new Date().getTime();
if(!fs.existsSync("index2")) fs.mkdirSync("index2");
var maxnum = 0;
for (var i = 1; i < 1001; i++) {
    fs.writeFile("./index2/" + i + ".txt", "hi", (err, data) => {
        var EndTime1 = new Date().getTime();
        if (maxnum < (EndTime1 - StartTime1)) {
            maxnum = (EndTime1 - StartTime1);
        }
    });

}

setTimeout(function () {
    console.log("异步耗时为：" + maxnum);
}, 2000)

for (var a = 1; a < 1001; a++) {
    fs.readFile("./index/" + a + ".txt", 'utf-8', (err, data) => {
        console.log(data.toString());
    })
    fs.readFile("./index/" + a + ".txt", 'ascii', (err, data) => {
        console.log(data.toString());
    })
    fs.readFile("./index2/" + a + ".txt", 'utf-8', (err, data) => {
        console.log(data.toString());
    })
    fs.readFile("./index2/" + a + ".txt", 'ascii', (err, data) => {
        console.log(data.toString());
    })
}